#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>

#include <grpc/grpc.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "hello.pb.h"
#include "hello.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;
using std::chrono::system_clock;

using namespace hello;
using namespace std;

class HelloServer final : public ExampleService::Service {
 public:
  explicit HelloServer() {
    cout << "new obj..." << endl;
  }

    virtual Status SayHi(ServerContext* context, const HelloRequest* request, HelloResponse* response) {
        response->set_message(request->name() + 1000);
        return Status::OK;
    }
    virtual Status SayHiStreamly(ServerContext* context, const HelloRequest* request, ServerWriter< HelloResponse>* writer) {
        int i = 0;
        while (1) {
            HelloResponse response;
            
            response.set_message(++i + request->name());
            writer->Write(response);
            sleep(1);
        }
        return Status::OK;
    }
  
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  HelloServer service;

  ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}
